package cn.dansj.common.utils.spring.context;

import cn.dansj.common.processor.meta.WriteToAutoConfiguration;
import cn.dansj.common.utils.spring.context.condition.ConditionalOnClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

/**
 * springCloud更新了配置自动刷新之后ApplicationContextProvider所持有的旧的applicationContext就会被关闭
 * </br>
 * 需要在这里监听重新注入applicationContext
 */
@ConditionalOnClass({RefreshScopeRefreshedEvent.class})
@WriteToAutoConfiguration
public class ApplicationContextRefresh {
    private final ConfigurableApplicationContext applicationContext;
    private static final Logger logger = LoggerFactory.getLogger(ApplicationContextRefresh.class);

    public ApplicationContextRefresh(ConfigurableApplicationContext applicationContext) {
        logger.info("<<<<<< ApplicationContextRefresh ready >>>>>>");
        this.applicationContext = applicationContext;
    }

    /**
     * 监听上下文刷新事件
     */
    @EventListener({RefreshScopeRefreshedEvent.class, ContextRefreshedEvent.class})
    public void handleRefreshRoutesEvent() {
        ApplicationContextProvider.injectApplicationContext(applicationContext);
        // 重新刷新配置信息
        if (applicationContext.isActive()) GetEnvironment.getEnvironmentMapData();
    }
}